package com.xo.user.until;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class JwtUtil {

    public static final long JWT_TTL = 60 * 60 * 24;

    public static final String JWT_KEY = "dayuMallJwtKeydayuMallJwtKeydayuMallJwtKeydayuMallJwtKeydayuMallJwtKey";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String createJWT(String subject, Long ttlMillis, String uuid) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, uuid);
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm hs256 = SignatureAlgorithm.HS256;
        SecretKey secretKey = generateSecretKey();
        long nowMillis = System.currentTimeMillis();
        long expireMillis = nowMillis + ttlMillis;
        Date expireDate = new Date(expireMillis);
        return Jwts.builder()
                .setId(uuid)    //设置 JWT 的唯一标识
                .setSubject(subject)    //设置 JWT 的主题
                .setIssuer("dayu")  //设置 JWT 的发行者，通常是你的应用或服务名称
                .setIssuedAt(new Date(nowMillis))   //设置 JWT 的签发时间
                .signWith(secretKey, hs256)     //使用指定的算法和密钥进行签名
                .setExpiration(expireDate);     //设置 JWT 的过期时间
    }

    private static SecretKey generateSecretKey() {
        byte[] decode = Base64.getDecoder().decode(JWT_KEY);
        return new SecretKeySpec(decode, 0, decode.length, "HmacSHA256");
    }

    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generateSecretKey();
        return Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(jwt)
                .getBody();
    }


}
